package com.ojoin.trade.common.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.ojoin.trade.common.Constants;
import com.ojoin.trade.common.exception.BusinessException;

/**
 * 转换html文件为pdf文件 工具类
 * 
 * @author guoting
 * 
 */
public class Html2PDFAsianUtil {

	/**
	 * 生成pdf文件
	 * 
	 * @param htmlFilePath
	 * @param pdfFilePath
	 * @throws IOException
	 * @throws DocumentException
	 */
	public void createPdf(String htmlFilePath, String pdfFilePath)
			throws IOException, DocumentException, BusinessException {
		// step 1
		Document document = new Document();
		// step 2
		PdfWriter writer = PdfWriter.getInstance(document,
				new FileOutputStream(pdfFilePath));
		// step 3
		document.open();
		// step 4
		XMLWorkerHelper.getInstance().parseXHtml(writer, document,
				new FileInputStream(htmlFilePath), Charset.forName(Constants.ENCODING));
		// step 5
		document.close();
	}

	/**
	 * 替换模板文件中的占位符为map中数据
	 * 
	 * @param templatefilename
	 * @param generatefilename
	 * @param replaceMap
	 */
	public void replace(InputStream templatefilePath, String generatefilename,
			HashMap<String, String> replaceMap) throws BusinessException {
		try {
			BufferedReader bf = new BufferedReader(new InputStreamReader(
					templatefilePath, Charset.forName(Constants.ENCODING)));

			// make sure pDir is exist
			File f = new File(generatefilename);
			File pf = f.getParentFile();
			FileUtils.forceMkdir(pf);

			OutputStreamWriter write = new OutputStreamWriter(
					new FileOutputStream(f), Constants.ENCODING);
			BufferedWriter bw = new BufferedWriter(write);

			String s = null;
			while ((s = bf.readLine()) != null) {
				if (replaceMap != null && replaceMap.size() > 0) {
					Set<String> keySet = replaceMap.keySet();
					Iterator<String> iterator = keySet.iterator();
					while (iterator.hasNext()) {
						String source = iterator.next();
						String target = replaceMap.get(source);
						if (StringUtils.isEmpty(source)
								|| StringUtils.isEmpty(target))
							continue;
						s = s.replaceAll(source, target);
					}
				}
				bw.write(s);
				bw.newLine();
				bw.flush();
			}
			bw.close();
			bf.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String generatePDFFileByMhtno(HashMap<String, String> replaceMap,
			String targetPDFFileFolder, String targetPDFFilename,
			InputStream templatefilePath, String filePrefix, String contactno)
			throws BusinessException {
		String htmldest = targetPDFFileFolder + File.separator + targetPDFFilename + ".html";
		replace(templatefilePath, htmldest, replaceMap);
		String pdfdest = targetPDFFileFolder + File.separator + targetPDFFilename + ".pdf";
		File file = new File(pdfdest);
		file.getParentFile().mkdirs();
		try {
			createPdf(htmldest, pdfdest);
			return pdfdest;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (BusinessException e) {
			throw e;
		}

		return null;
	}

	public static void main(String[] args) throws IOException,
			DocumentException {
		// int joinuserid = 4;
		// MerchantUserInfo vo = new MerchantUserInfo();
		// vo.setMchName("测试mchname");
		// vo.setMchType("测试mchtype");
		// vo.setMobile("13521844691");
		//
		// String fee = "5";
		String targetPath = "C:/doc2pdf3";

		// AccountInfoVO accountinfovo = new AccountInfoVO();
		// accountinfovo.setAccno("accno测试");
		// accountinfovo.setBankMan("bankMan测试");
		// accountinfovo.setSettleAccno("settleAccno测试");
		// accountinfovo.setBankName("bankName测试");
		// accountinfovo.setBankBranch("bankBranch测试");
		// accountinfovo.setRate("rate测试");
		// HashMap<String, String> map = new HashMap<String, String>();
		// new Html2PDFAsianUtil().generateContractFileByMhtno(joinuserid, vo,
		// accountinfovo, targetPath,fee);
		// new Html2PDFAsianUtil().generateAccChangeFileByMhtno(vo,
		// accountinfovo, targetPath);
		// new Html2PDFAsianUtil().generateSLContractFileByMhtno(map
		// ,joinuserid, vo, accountinfovo, targetPath);
//		new Html2PDFAsianUtil().generateSLLoanApplyFileByMhtno(null, null,
//				targetPath);

	}

}